import { pxChangeRem, insertAdvert } from "@/utils";
import { queryNewsList } from "@/api/news";
export default function useNews() {
  const route = useRoute();
  const newsList = ref<any[]>([]);
  const page = ref(1);
  const newsLoadMoreStatus = ref<"loadmore" | "loading" | "nomore">("loadmore");
  const loadNews = async () => {
    if (newsLoadMoreStatus.value === "loadmore") {
      newsLoadMoreStatus.value = "loading";
      page.value += 1;
      fetchNews(unref(page));
    }
  };
  const fetchNews = (page: number) => {
    queryNewsList(page, route.params.id).then((res: any) => {
      const data = (res || []).map((item: any) => ({
        id: item.id,
        src: item.image,
        title: item.title,
        time: item.time,
        author: item.author,
        type: "news",
        imgWidth: "100%",
        imgHeight: pxChangeRem(100)
      }));
      if (data.length < 6) {
        newsLoadMoreStatus.value = "nomore";
      } else {
        newsLoadMoreStatus.value = "loadmore";
      }
      const lastAdvertIndex = unref(newsList).findLastIndex(
        (item: any) => item.type === "advert"
      );
      let lastEles = [];
      let preEles = [];
      if (lastAdvertIndex !== -1) {
        lastEles = unref(newsList).slice(lastAdvertIndex + 1);
        preEles = unref(newsList).slice(0, lastAdvertIndex + 1);
      } else {
        preEles = [];
        lastEles = [...unref(newsList)];
      }
      const currData = insertAdvert(
        [...lastEles, ...data],
        { type: "advert", source: "news" },
        5
      );
      newsList.value = preEles.concat(currData);
    });
  };
  onMounted(() => {
    fetchNews(unref(page));
  });
  return { newsList, loadNews, newsLoadMoreStatus };
}
